package com.lcx.movie.controller;

import com.lcx.movie.common.Rep;
import com.lcx.movie.entity.*;
import com.lcx.movie.service.*;
import io.minio.MinioClient;
import io.minio.ObjectWriteResponse;
import io.minio.PutObjectArgs;
import org.apache.ibatis.annotations.Param;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;

import java.io.FileInputStream;
import java.io.InputStream;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

/**
 * @author 李丽君
 * @version 1.0
 * @Description Minio的控制层
 * @date 2024/12/19 11:17
 */
// 匹配所有请求 [允许跨域访问]
@CrossOrigin(origins = "*")
@RestController
public class MinioController {
    @Autowired
    MinioClient minioClient;
    @Autowired
    private MovieDetailService movieDetailService;
    /**
     * 测试minio是否可用
     * @return Rep对象信息
     */
    @GetMapping("/upload")
    public Rep upload() throws Exception {
        // 定义文件名
        String fileName="命令.txt";
        // 定义文件上传的路径
        String filepath="C:\\Users\\Administrator\\Desktop\\命令.txt";
        // 创建数据流
        FileInputStream inputStream = new FileInputStream(filepath);
        // 上传到minio服务器
        ObjectWriteResponse objectWriteResponse = minioClient
          .putObject(PutObjectArgs.builder()
                .bucket("moviebucket")
                .object(fileName)
                .stream(inputStream, -1L, 10485760L)
                .build());
        return new Rep().addData("fileMessage",objectWriteResponse.object());
    }

    /**
     * 新增用户头像
     * @param file 文件对象
     * @return rep对象
     * @throws Exception 抛出异常
     */
    @PostMapping("/upload3")
    public Rep upload3(@RequestParam("file") MultipartFile file) throws Exception {
        // 1,存储上传的文件信息
        InputStream fileInputStream=file.getInputStream();
        String fileName=System.currentTimeMillis()+"/"+file.getOriginalFilename();
        // 用户头像对象
        MovieDetail movieDetail=new MovieDetail();
        // 将路径存入对象中
        movieDetail.setImgAddress(fileName);
        // save[存入的方法]
        this.movieDetailService.save(movieDetail);
        // 2,上传到minio服务器
        ObjectWriteResponse objectWriteResponse=minioClient.putObject(
                PutObjectArgs.builder()
                        .bucket("moviebucket")
                        .object(fileName)
                        .stream(fileInputStream,-1L,10485760L)
                        .build()
        );
        return new Rep().addData("fileMessage",objectWriteResponse.object());
    }
    @PostMapping("/upload4")
    public Rep upload4(@RequestParam("file") MultipartFile file, @Param("movieId") Integer movieId) throws Exception {
        // 1,存储上传的文件信息
        InputStream fileInputStream=file.getInputStream();
        String fileName=System.currentTimeMillis()+"/"+file.getOriginalFilename();
        System.out.println("movieId ============== " + movieId);
        MovieDetail movieDetail=new MovieDetail();
        // 将路径存入对象中
        movieDetail.setImgAddress(fileName);
        movieDetail.setMovieId(movieId);
        // save[存入的方法]
        this.movieDetailService.save(movieDetail);
        // 2,上传到minio服务器
        ObjectWriteResponse objectWriteResponse=minioClient.putObject(
                PutObjectArgs.builder()
                        .bucket("moviebucket")
                        .object(fileName)
                        .stream(fileInputStream,-1L,10485760L)
                        .build()
        );
        return new Rep().addData("fileMessage",objectWriteResponse.object()).addData("code",0);
    }
    @Autowired
    private UserService userService;

    /**
     * 修改用户头像
     * @param file 文件对象
     * @param userId 用户id
     * @return rep对象
     * @throws Exception 抛出异常
     */
    @PostMapping("/upload5")
    public Rep upload5(@RequestParam("file") MultipartFile file, @RequestParam("userId") Integer userId) throws Exception {
        // 1,存储上传的文件信息
        InputStream fileInputStream=file.getInputStream();
        String fileName=System.currentTimeMillis()+"/"+file.getOriginalFilename();
        System.out.println("userId ============== " + userId);
        // 用户头像对象
        User user=new User();
        // 将路径存入对象中
        user.setUserHeadimg(fileName);
        user.setUserId(Long.valueOf(userId));
        // 调用修改用户头像的方法
        this.userService.updateUserHeadImg(user);
        //this.userimgsService.save(userimgs);
        // 2,上传到minio服务器
        ObjectWriteResponse objectWriteResponse=minioClient.putObject(
                PutObjectArgs.builder()
                        .bucket("moviebucket")
                        .object(fileName)
                        .stream(fileInputStream,-1L,10485760L)
                        .build()
        );
        return new Rep().addData("fileMessage",objectWriteResponse.object());
    }
    @Autowired
    private MovieService movieService;

    /**
     * 修改电影图片
     * @param file 文件对象
     * @param movieId 电影id
     * @return rep对象
     * @throws Exception 抛出异常
     */
    @PostMapping("/upload6")
    public Rep upload6(@RequestParam("file") MultipartFile file, @RequestParam("movieId") Integer movieId) throws Exception {
        // 1,存储上传的文件信息
        InputStream fileInputStream=file.getInputStream();
        String fileName=System.currentTimeMillis()+"/"+file.getOriginalFilename();
        System.out.println("movieId ============== " + movieId);
        //电影对象
        Movie movie=new Movie();
        // 将路径存入对象中
        movie.setMoviePicture(fileName);
        movie.setMovieId(Long.valueOf(movieId));
        // 调用单独修改电影海报的方法
        this.movieService.updateMovieImg(movie);
        // 2,上传到minio服务器
        ObjectWriteResponse objectWriteResponse=minioClient.putObject(
                PutObjectArgs.builder()
                        .bucket("moviebucket")
                        .object(fileName)
                        .stream(fileInputStream,-1L,10485760L)
                        .build()
        );
        return new Rep().addData("fileMessage",objectWriteResponse.object());
    }
    @Autowired
    private ActorService actorService;

    /**
     * 修改演员图片
     * @param file 文件对象
     * @param actorName 演员名称
     * @return rep对象
     * @throws Exception 抛出异常
     */
    @PostMapping("/uploadActor")
    public Rep uploadActor(@RequestParam("file") MultipartFile file, @RequestParam("actorName") String actorName) throws Exception {
        // 1,存储上传的文件信息
        InputStream fileInputStream = file.getInputStream();
        String fileName = System.currentTimeMillis() + "/" + file.getOriginalFilename();
        Actor actor = new Actor();
        // 将路径存入对象中
        actor.setActorImagePath(fileName);
        actor.setActorName(actorName); // 将获取到的演员姓名设置到actor对象中
        // save[存入的方法]
        this.actorService.insertActor(actor);
        // 2,上传到minio服务器
        ObjectWriteResponse objectWriteResponse = minioClient.putObject(
                PutObjectArgs.builder()
                        .bucket("moviebucket")
                        .object(fileName)
                        .stream(fileInputStream, -1L, 10485760L)
                        .build()
        );
        return new Rep().addData("fileMessage", objectWriteResponse.object());
    }
    @Autowired
    private SnacksService snacksService;

    /**
     * 修改零食信息
     * @param snackName 零食名称
     * @param price 价格
     * @param stockQuantity 零食库存
     * @param snackType 零食类型
     * @param file 文件对象
     * @return rep对象
     * @throws Exception 抛出异常
     */
    @PostMapping("/uploadSnacks")
    public Rep uploadSnacks(
            @RequestParam("snackName") String snackName,
            @RequestParam("price") Integer price,
            @RequestParam("stockQuantity") Integer stockQuantity,
            @RequestParam("snackType") String snackType,
            @RequestParam("file") MultipartFile file) throws Exception {
        Logger logger = LoggerFactory.getLogger(getClass());
        logger.info("Received request with parameters: snackName={}, price={}, stockQuantity={}, snackType={}, fileName={}",
                snackName, price, stockQuantity, snackType, file.getOriginalFilename());

        // 1,存储上传的文件信息
        InputStream fileInputStream = file.getInputStream();
        String fileName = System.currentTimeMillis() + "/" + file.getOriginalFilename();
        Snacks snacks = new Snacks();
        // 将路径存入对象中
        snacks.setDescription(fileName);
        snacks.setSnackName(snackName);
        snacks.setPrice(price);
        snacks.setSnackType(snackType);
        snacks.setStockQuantity(stockQuantity);
        // 2,上传到minio服务器
        ObjectWriteResponse objectWriteResponse = minioClient.putObject(
                PutObjectArgs.builder()
                        .bucket("moviebucket")
                        .object(fileName)
                        .stream(fileInputStream, -1L, 10485760L)
                        .build()
        );
        return new Rep().addData("fileMessage", objectWriteResponse.object()).addData("code", 0);
    }

    /**
     * 修改零食图片
     * @param file 文件对象
     * @param snackId 零食id
     * @return rep对象
     * @throws Exception 抛出异常
     */
    @PostMapping("/uploadSnacksPicture")
    public Rep uploadSnacksPicture(@RequestParam("file") MultipartFile file, @RequestParam("snackId") Integer snackId) throws Exception {
        if (file.isEmpty() || snackId == null) {
            throw new IllegalArgumentException("文件或零食ID不能为空");
        }
        // 处理文件上传逻辑
        InputStream fileInputStream = file.getInputStream();
        String fileName = System.currentTimeMillis() + "/" + file.getOriginalFilename();
        Snacks snacks = new Snacks();
        snacks.setDescription(fileName);
        snacks.setSnackId(snackId);
        // 调用服务层方法
        this.snacksService.updateSnacksPicture(snacks);
        // 上传到 MinIO
        ObjectWriteResponse objectWriteResponse = minioClient.putObject(
                PutObjectArgs.builder()
                        .bucket("moviebucket")
                        .object(fileName)
                        .stream(fileInputStream, -1L, 10485760L)
                        .build()
        );
        return new Rep().addData("fileMessage", objectWriteResponse.object());
    }
}
